package com.lry.core;

import java.util.List;
import java.util.TreeMap;

public class MemoryRaftLog implements RaftLog{


    private TreeMap<Long,Log> logMap = new TreeMap<>();


    @Override
    public long append(List<Log> logs){
        long curIndex = 0;
        for (Log log : logs) {
            curIndex = append(log);
        }
        return curIndex;
    }

    @Override
    public long append(Log log){
        long curIndex = getLastLogIndex()+1;
        log.setIndex(curIndex);
        logMap.put(curIndex,log);
        return curIndex;
    }

    @Override
    public Log getLastLog(){
        if(logMap.isEmpty()){
            return null;
        }
        return logMap.lastEntry().getValue();
    }

    @Override
    public long getLastLogIndex(){
        if(logMap.isEmpty()){
            return -1;
        }
        return logMap.lastKey();
    }

    @Override
    public Log getEntry(long index) {
        return logMap.get(index);
    }

    @Override
    public long getEntryTerm(long index){
        Log log = getEntry(index);
        if(null==log){
            return 0;
        }
        return log.getTerm();
    }

    @Override
    public void truncateSuffix(long lastIdx){
        while(true){
            long lastLogIndex = getLastLogIndex();
            if(lastLogIndex>=lastIdx){
                logMap.remove(lastLogIndex);
            }
        }
    }


}
